package com.cxs.controller;

import com.cxs.model.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/*
 * @Project:spring-boot-shiro-demo
 * @Author:cxs
 * @Motto:放下杂念,只为迎接明天更好的自己
 * */
@Controller
public class AuthController {

    /**
     * 用户认证接口
     * @param request
     * @param model
     * @param username
     * @param password
     * @return
     */
    @PostMapping("/auth/login")
    public String authLogin(HttpServletRequest request, Model model, String username, String password){
        if (!StringUtils.hasLength(username)) {
            model.addAttribute("msg", "用户名不能为空");
            return "login";
        }
        if (!StringUtils.hasLength(password)) {
            model.addAttribute("msg", "密码不能为空");
            return "login";
        }
        // 获取当前用户主体
        Subject subject = SecurityUtils.getSubject();
        // 将用户名和密码封装成 UsernamePasswordToken 对象
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username.trim(), password.trim());
        // 执行认证流程，走我们的自定义realm
        subject.login(usernamePasswordToken);
        // 登录成功,将用户信息存于session
        HttpSession session = request.getSession();
        // 这里获取的载荷是realm中决定的
        User user = (User) subject.getPrincipal();
        session.setAttribute("user", user);
        return "index";
    }
}
